package com.xinyue.game.server.dispatcher;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import com.xinyue.game.server.codec.message.GameMessageMeta;
import com.xinyue.game.server.codec.message.IGameMessage;

@Service
public class GameMessageDispatcher {
	private Logger logger = LoggerFactory.getLogger(GameMessageDispatcher.class);
	private Map<Integer, Class<?>> gameMessageClassMap = new HashMap<>();
	private Map<Integer, GameMessageHandlerMapping> handlerMethodMap = new HashMap<>();
	@Autowired
	private ApplicationContext context;

	@PostConstruct
	public void init() {
		String[] beanNames = context.getBeanNamesForAnnotation(GameMessageHandler.class);
		if (beanNames != null && beanNames.length > 0) {
			for (String beanName : beanNames) {
				Object beanObject = context.getBean(beanName);
				Method[] methods = beanObject.getClass().getMethods();
				if (methods != null && methods.length > 0l) {
					for (Method method : methods) {
						GameMessageRequest gameMessageRequest = method.getAnnotation(GameMessageRequest.class);
						if (gameMessageRequest != null) {
							Class<?>[] types = method.getParameterTypes();
							int messageId = getMessageId(types[0]);
							gameMessageClassMap.put(messageId, types[0]);
							GameMessageHandlerMapping gameMessageHandlerMapping = new GameMessageHandlerMapping(
									beanObject, method);
							handlerMethodMap.put(messageId, gameMessageHandlerMapping);
						}
					}
				}
			}
		}
	}

	private int getMessageId(Class<?> clazz) {
		GameMessageMeta meta = clazz.getAnnotation(GameMessageMeta.class);
		int messageId = 0;
		if (meta != null) {
			messageId = meta.messageId();
		}
		return messageId;
	}

	public IGameMessage getGameMessageRequestInstance(int messageId) {
		Class<?> clazz = gameMessageClassMap.get(messageId);
		if (clazz == null) {
			logger.error("找不到消息号:{}对应的对象类", messageId);
			return null;
		}
		try {
			Object instance = clazz.getConstructor().newInstance();
			return (IGameMessage) instance;
		} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
				| NoSuchMethodException | SecurityException e) {
			logger.error("消息号为：{} 的对象创建失败", messageId, e);
		}
		return null;
	}

	public void callMethod(IGameMessage request, GameServerContext stx) throws GameServerException {
		int messageId = request.getHeader().getMessageId();
		GameMessageHandlerMapping messageHandlerMapping = handlerMethodMap.get(messageId);
		if (messageHandlerMapping == null) {
			logger.error("未找到处理消息：{}的方法", messageId);
			return;
		}
		Object handlerObj = messageHandlerMapping.getHandlerObject();
		Method handlerMethod = messageHandlerMapping.getHandlerMehtod();
		try {
			handlerMethod.invoke(handlerObj, request, stx);
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			logger.error("消息号：{}的消息：{}处理失败", messageId, request.getClass().getName(), e);
			GameServerException exp = new GameServerException();
			throw exp;
		}
	}
}
